package com.metrics.graphics;

import static com.metrics.utils.GraphicUtil.*;

import java.awt.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.List;

import org.jfree.chart.*;
import org.jfree.chart.labels.*;
import org.jfree.chart.plot.*;
import org.jfree.data.general.*;

import com.database.objects.*;
import com.metrics.extractors.*;
import com.metrics.formatters.*;

public class GraphicPieGenerator extends GraphicGenerator {

	@Override
	public AbstractDataset getData(List<Developer> developers, MetricExtractor extractor, Type type, Status status, String start, String finish, TimeFormatter formatter) {
		DefaultPieDataset data = new DefaultPieDataset();
		Double sum = 0.0;
		Double total = developers.isEmpty() ? 0 : extractor.extractTotal(developers.get(0).getProject(), type, status, start, finish);
		for (Developer developer : developers) {
			Double percent = (developer.getValue() / total) * 100.0;
			data.setValue(developer.getName(), percent);
			sum += percent;
		}

		Double difference = 100.0 - sum;
		if (difference.compareTo(0.5) > 0) {
			data.setValue("NO CALCULATED", difference);
		}
		return data;
	}

	@Override
	public void graphic(OutputStream out, AbstractDataset data) throws IOException {
		JFreeChart chart = ChartFactory.createPieChart("", (PieDataset) data, true, false, false);
		decoratePieChart(chart);
		ChartUtilities.writeChartAsPNG(out, chart, WIDTH, HEIGHT);
	}

	private void decoratePieChart(JFreeChart chart) {
		PiePlot plot = (PiePlot) chart.getPlot();
		plot.setBackgroundPaint(Color.WHITE);
		plot.setShadowPaint(Color.WHITE);
		plot.setLabelGenerator(null);
		plot.setLegendLabelGenerator(new CustomLegendGenerator());
	}

	public static class CustomLegendGenerator implements PieSectionLabelGenerator {

		@Override
		@SuppressWarnings("unchecked")
		public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key) {
			return null;
		}

		@Override
		@SuppressWarnings("unchecked")
		public String generateSectionLabel(PieDataset dataset, Comparable key) {
			BigDecimal value = new BigDecimal(dataset.getValue(key).toString());
			value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
			return key.toString() + "= " + value.toString();
		}

	}

}